package com.app.bimo.library_db.helper;

import com.app.bimo.commonbusiness.util.RxBus;
import com.app.bimo.library_db.BookRecord;
import com.app.bimo.library_db.ChapterData;
import com.app.bimo.library_db.ChapterRecord;
import com.app.bimo.library_db.dao.BookRecordDao;
import com.app.bimo.library_db.dao.ChapterDataDao;
import com.app.bimo.library_db.dao.ChapterRecordDao;
import com.app.bimo.library_db.dao.DaoSession;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;


public class ChapterHelper {
    private static volatile ChapterHelper sInstance;
    private DaoSession mSession;
    private ChapterDataDao mChapterDao;
    private ChapterRecordDao mChapterRecordDao;

    private ChapterHelper() {
        mSession = DaoDbHelper.getInstance()
                .getSession();
        mChapterDao = mSession.getChapterDataDao();
        mChapterRecordDao = mSession.getChapterRecordDao();
    }

    public static ChapterHelper getInstance() {
        if (sInstance == null) {
            synchronized (ChapterHelper.class) {
                if (sInstance == null) {
                    sInstance = new ChapterHelper();
                }
            }
        }
        return sInstance;
    }

    /**
     * 异步存储BookChapter
     *
     * @param beans
     */
    public void saveBookChaptersWithAsync(List<ChapterData> beans) {
        mSession.startAsyncSession()
                .runInTx(
                        () -> {
                            //存储BookChapterBean
                            mChapterDao
                                    .insertOrReplaceInTx(beans);
                        }
                );
    }

    /**
     * 异步存储BookChapter
     *
     * @param bean
     */
    public void saveBookChaptersWithAsync(ChapterData bean) {
        mSession.startAsyncSession()
                .runInTx(
                        () -> {
                            //存储BookChapterBean
                            mChapterDao
                                    .insertOrReplaceInTx(bean);
                        }
                );
    }

    List<ChapterData> getBookChapters(String novelid) {
        return mChapterDao
                .queryBuilder()
                .where(ChapterDataDao.Properties.Novelid.eq(novelid))
                .orderAsc(ChapterDataDao.Properties.ChapterNumber)
                .list();
    }

    public List<ChapterData> getBookChapters(String novelid, String chapterids) {
        String[] temps = chapterids.split(",");
        List<String> ids = new ArrayList<>();
        for (String str : temps) {
            ids.add(str);
        }
        return mChapterDao
                .queryBuilder()
                .where(ChapterDataDao.Properties.Novelid.eq(novelid), ChapterDataDao.Properties.Chapterid.in(ids))
                .orderAsc(ChapterDataDao.Properties.ChapterNumber)
                .list();
    }

    public ChapterData getChapterData(String novelid, String chapterid) {

        return mChapterDao
                .queryBuilder()
                .where(ChapterDataDao.Properties.Novelid.eq(novelid), ChapterDataDao.Properties.Chapterid.eq(chapterid)).unique();
    }

    /**
     * 是否是最后一章
     *
     * @param novelid
     * @param chapterid
     * @return
     */
    public boolean isLastChapter(String novelid, String chapterid) {
        List<ChapterData> lists = mChapterDao.queryBuilder().where(ChapterDataDao.Properties.Novelid.eq(novelid)).orderDesc(ChapterDataDao.Properties.ChapterNumber).list();
        if (lists == null) {
            return false;
        }
        return lists.get(0).getChapterid().equals(chapterid);
    }

    public Observable<List<ChapterData>> localObservable(String novelid) {
        return Observable.just(getBookChapters(novelid));
    }

    public boolean isHaveCache(String novelid) {
        return mChapterDao
                .queryBuilder()
                .where(ChapterDataDao.Properties.Novelid.eq(novelid)).count() != 0;
    }

    public Observable<List<ChapterData>> localObservable(String novelid, String chapterids) {
        return Observable.just(getBookChapters(novelid, chapterids));
    }

    //获取阅读记录
    public BookRecord getBookRecord(String bookId, String uid) {
        BookRecord bookRecord = mSession.getBookRecordDao()
                .queryBuilder()
                .where(BookRecordDao.Properties.BookId.eq(bookId), BookRecordDao.Properties.Uid.eq(uid))
                .unique();
        if (bookRecord == null) {
            bookRecord = new BookRecord();
            bookRecord.setUid(uid);
        }
        return bookRecord;
    }

    public void deleteBookRecord(String bookId, String uid){
        if (bookId != null){
            BookRecord bookRecord = mSession.getBookRecordDao()
                    .queryBuilder()
                    .where(BookRecordDao.Properties.BookId.eq(bookId), BookRecordDao.Properties.Uid.eq(uid))
                    .unique();

            if (bookRecord != null){
                mSession.getBookRecordDao().delete(bookRecord);
            }
        }else{
            mSession.getBookRecordDao().deleteAll();
        }

    }



    public void saveBookRecord(BookRecord bean) {
        mSession.getBookRecordDao()
                .insertOrReplace(bean);
    }

    public boolean isDown(String id, String uid) {
        return mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(id), ChapterRecordDao.Properties.Uid.eq(uid), ChapterRecordDao.Properties.IsDown.eq(1)).count() != 0;
    }

    /**
     * 下载页面删除书籍  要改变章节下载状态为未下载
     */
    public void delDownLoadBook(String novelid, String uid) {
        List<ChapterRecord> records = mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.NovelId.eq(novelid), ChapterRecordDao.Properties.Uid.eq(uid)).list();
        for (int i = 0; i < records.size(); i++) {
            records.get(i).setIsDown(0);
            mChapterRecordDao.update(records.get(i));

        }
    }

    /**
     * 获取一批是否都被下载过
     *
     * @param startChapterId 当前章节id
     * @param chapterNum     后30  50  100章
     * @param uid            用户id
     * @return 已经下载了  true  没有下载  返回false
     */
    public boolean isDown(String nid, String startChapterId, String uid, int chapterNum) {
        ChapterData data = mChapterDao.queryBuilder().where(ChapterDataDao.Properties.Chapterid.eq(startChapterId)).unique();


//        QueryBuilder<ChapterData> queryBuilder = mChapterDao.queryBuilder().where(ChapterDataDao.Properties.ChapterNumber.ge(data.getChapterNumber())).limit(chapterNum);

//        queryBuilder.join(ChapterData.class, ChapterRecordDao.Properties.ChapterId)
//                .where(ChapterRecordDao.Properties.NovelId.eq(data.getNovelid()), ChapterRecordDao.Properties.Uid.eq(uid), ChapterRecordDao.Properties.IsDown.eq(1));


//        List<ChapterData> records = queryBuilder.list();
//        if (records == null || records.size() == 0) {
//            return false;
//        } else {
//            return true;
//        }


        List<ChapterData> chapterDatas = null;
        if (data == null) {
            return false;
        }
        if (data != null) {
            chapterDatas = mChapterDao.queryBuilder().where(ChapterDataDao.Properties.Novelid.eq(nid), ChapterDataDao.Properties.ChapterNumber.ge(data.getChapterNumber()),
                    ChapterDataDao.Properties.ChapterNumber.le(data.getChapterNumber() + chapterNum - 1)).limit(chapterNum).list();
            if (chapterDatas == null && chapterDatas.size() == 0) {
                return false;
            }
            if (chapterDatas.size() < chapterNum) {
                return false;
            }
            for (int i = 0; i < chapterDatas.size(); i++) {
//                String id = MD5Utils.strToMd5By16(chapterDatas.get(i).getChapterid() + nid);
                String id = chapterDatas.get(i).getChapterid() + nid;
                ChapterRecord record = mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(id), ChapterRecordDao.Properties.Uid.eq(uid), ChapterRecordDao.Properties.IsDown.eq(1)).unique();
                if (record == null) {
                    return false;
                }
            }
        }
        return true;
    }

    public ChapterRecord getChapterRecord(String nid, String chapterID, String uid) {
        return mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.NovelId.eq(nid), ChapterRecordDao.Properties.ChapterId.eq(chapterID), ChapterRecordDao.Properties.Uid.eq(uid)).unique();
    }




    public boolean isRead(String id, String uid) {
        return mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(id), ChapterRecordDao.Properties.Uid.eq(uid), ChapterRecordDao.Properties.IsRead.eq(1)).count() != 0;
    }

    public void updateChapterDown(List<ChapterRecord> chapterRecords) {
//        mSession.startAsyncSession().runInTx(() -> {
//            List<ChapterRecord> chapterRecordList = new ArrayList<>();
//            List<ChapterRecord> chapterRecordList1 = new ArrayList<>();

        try {
            for (int i = 0; i < chapterRecords.size(); i++) {
                ChapterRecord chapterRecord = chapterRecords.get(i);
                if (mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(chapterRecord.getId())).unique() == null) {
//                    chapterRecordList.add(chapterRecord);
                    mChapterRecordDao.insertOrReplace(chapterRecord);
                } else {
                    ChapterRecord record = mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(chapterRecord.getId())).unique();
                    if (record.getIsDown() == 0) {
                        record.setIsDown(1);
                        mChapterRecordDao.update(record);
                    }
//                    chapterRecordList1.add(record);
                }
            }
            mChapterRecordDao.detachAll();
            RxBus.getInstance().post(new ChapterRecord());

        } catch (Exception e) {
//                Log.e("aaa", "updateChapterDown: " + e.toString());
        }
//        mChapterRecordDao.insertOrReplaceInTx(chapterRecordList);
//        mChapterRecordDao.updateInTx(chapterRecordList1);
//        });
    }

    public void updateChapterRecord(ChapterRecord chapterRecord) {
        mSession.startAsyncSession().runInTx(() -> {
            if (mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(chapterRecord.getId())).count() == 0) {
                mChapterRecordDao.insert(chapterRecord);
            } else {
                ChapterRecord record = mChapterRecordDao.queryBuilder().where(ChapterRecordDao.Properties.Id.eq(chapterRecord.getId())).unique();
                record.setIsRead(1);
                mChapterRecordDao.update(record);
            }
        });
    }




}
